package handler

import (
	"net/http"
	v1 "server_go/api/v1"
	"server_go/internal/service"
	"strconv"

	"github.com/gin-gonic/gin"
)

type AdminHandler struct {
	*Handler
	adminService service.AdminService
}

func NewAdminHandler(
	handler *Handler,
	adminService service.AdminService,
) *AdminHandler {
	return &AdminHandler{
		Handler:      handler,
		adminService: adminService,
	}
}

func (h *AdminHandler) Login(ctx *gin.Context) {
	req := new(v1.LoginRequest)
	if err := ctx.ShouldBindJSON(req); err != nil {
		v1.HandleError(ctx, http.StatusBadRequest, err, nil)
		return
	}
	admin, token, err := h.adminService.Login(ctx, *req)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, v1.LoginResponse{
		Token: token,
		Name:  admin.Name,
		Id:    admin.ID,
	})
}
func (h *AdminHandler) DeleteUser(ctx *gin.Context) {
	UserId := ctx.Param("userId")
	if UserId == "" {
		v1.HandleError(ctx, http.StatusBadRequest, nil, gin.H{"error": "用户不存在"})
		return
	}
	userId, _ := strconv.Atoi(UserId)
	if err := h.adminService.DeleteUser(ctx, uint(userId)); err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, nil)
}

// 查询所有用户
func (h *AdminHandler) GetUsers(ctx *gin.Context) {
	users, err := h.adminService.GetUsers(ctx)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, users)
}
